import React, { useState } from 'react';
import { Image, View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import CommentImagePreview from '@/components/Comment/ImagePreview';
import { connect } from 'react-redux';
import picPhoto from './icon_photo.png';
import picClose from './icon_close.png';

import './index.scss';

//图片选择器
const CommentImagePicker = ({
  dispatch,
  columnCount = 3,
  limitCount = 9,
  from = 'comment',
  onChange = () => {},
}) => {
  const [state, updateState] = useState({
    files: [],
  });

  const setState = (val) => {
    const res = { ...state, ...val };
    updateState(res);
    onChange(res.files);
  };

  //选择图片
  const chooseImage = () => {
    Taro.chooseImage({
      count: limitCount - state.files.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function (res) {
        if (state.files.length + res.tempFilePaths.length > limitCount) {
          Taro.showToast({
            title: `最多上传${limitCount}张图片`,
            duration: 1000,
            icon: 'none',
          });
        } else {
          setState({ files: state.files.concat(res.tempFilePaths) });
        }
      },
    });
  };

  //删除图片
  const delImage = (idx) => {
    //因渲染机制增加定时器
    setTimeout(() => {
      state.files.splice(idx, 1);
      setState({
        files: state.files,
      });
    }, 0);
  };

  const handleImage = (current) => {
    dispatch({
      type: 'globalComponent/previewImage',
      payload: {
        previewImage: {
          urls: state.files,
          current,
        },
      },
    });
  };

  //获取渲染数据
  const getBoxList = () => {
    let res = [];
    let data = state.files
      .map((item, index) => {
        return {
          type: 0,
          idx: index,
          data: item,
        };
      })
      .concat({ type: 1 })
      .concat(
        state.files.length < limitCount
          ? new Array(columnCount - 1 - (state.files.length % columnCount)).fill({ type: 2 })
          : [],
      );
    for (let i = 0; i < data.length; i = i + columnCount) {
      res.push(data.slice(i, i + columnCount));
    }
    return res;
  };

  return (
    <View className="commentImagePicker">
      <CommentImagePreview />
      {getBoxList().map((box, boxIdx) => (
        <View className="cpbox" key={boxIdx}>
          {box.map((item, idx) => {
            if (item.type == 0) {
              return (
                <View className="item" key={idx}>
                  <View className="con">
                    <Image
                      mode="aspectFill"
                      className="preview"
                      src={item.data}
                      onClick={() => handleImage(item.idx)}
                    />
                    <Image
                      onClick={() => {
                        delImage(item.idx);
                      }}
                      className="del"
                      src={picClose}
                    />
                  </View>
                </View>
              );
            } else if (item.type == 1) {
              return (
                state.files.length < limitCount && (
                  <View className="item" onClick={chooseImage} key={idx}>
                    <View className="con chooseImage">
                      <Image className="icon" src={picPhoto} />
                      {from == 'comment' && <Text>亮出买家秀</Text>}
                      {from == 'afterSale' && (
                        <Text className="txt22 grayC">
                          {state.files.length > 0
                            ? state.files.length + '/' + limitCount
                            : '上传照片'}
                        </Text>
                      )}
                      {from == 'afterSale' && (
                        <Text className="txt22 grayC">(最多{limitCount}张)</Text>
                      )}
                    </View>
                  </View>
                )
              );
            } else {
              return <View className="item" key={idx}></View>;
            }
          })}
        </View>
      ))}
    </View>
  );
};

export default connect(({}) => ({}))(CommentImagePicker);
